from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django.core.cache import cache

from .models import Area

# Create your views here.


# 获取省份数据
class ProvinceAreasView(View):

    def get(self, request):
        # 先读缓存
        # 读取缓存数据：cache.get('key')
        # 如果缓存数据存在返回列表，否则返回None
        province_list = cache.get("province_list")

        if province_list:
            return JsonResponse({
                "code": 0,
                "errmsg": "ok",
                "province_list": province_list
            })
        else:
            provinces = Area.objects.filter(parent=None)

            province_list = []
            for province in provinces:
                province_list.append({
                    "id": province.id,
                    "name": province.name
                })
            # 存储缓存数据：cache.set('key', 内容, 有效期)
            # 缓存时间设置为3600秒，目的：一定程度上可以实现"缓存弱一致"
            cache.set("province_list", province_list, 3600)

            return JsonResponse({
                "code": 0,
                "errmsg": "ok",
                "province_list": province_list
            })


# 获取市、区信息
class SubAreasView(View):

    def get(self, request, pk):

        sub_data = cache.get("sub_area_"+pk)
        if sub_data:
            return JsonResponse({
                "code": 0,
                "errmsg": "ok",
                "sub_data": sub_data
            })

        else:
            try:
                parent_area = Area.objects.get(pk=pk)
                sub_areas = Area.objects.filter(parent_id=pk)
                # sub_areas = Area.objects.filter(parent=parent_area)
            except Exception as e:
                return JsonResponse({'code': 400, 'errmsg': '数据库错误'})

            sub_list = []
            for sub in sub_areas:
                sub_list.append(
                    {
                        "id": sub.id,
                        "name": sub.name
                    }
                )

            sub_data = {
                "id": parent_area.id,
                "name": parent_area.name,
                "subs": sub_list
            }
            cache.set("sub_area_"+pk, sub_data, 3600)

            return JsonResponse({
                "code": 0,
                "errmsg": "ok",
                "sub_data": sub_data
            })



